package com.sc.service.serviceImpl;

import com.sc.common.pojo.CommonResult;
import com.sc.common.pojo.EasyUiTreeNode;
import com.sc.mapper.TbContentCategoryMapper;
import com.sc.pojo.TbContentCategory;
import com.sc.pojo.TbContentCategoryExample;
import com.sc.service.ContentCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sc on 2017/10/19.
 */
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {

    @Autowired
    private TbContentCategoryMapper contentCategoryMapper;

    public List<EasyUiTreeNode> getList(Long parentId) {
        TbContentCategoryExample example = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
        List<EasyUiTreeNode> easyUiTreeNodeList = new ArrayList<EasyUiTreeNode>();
        for(TbContentCategory item:list){
            EasyUiTreeNode easyUiTreeNode = new EasyUiTreeNode();
            easyUiTreeNode.setState(item.getIsParent()?"closed":"open");
            easyUiTreeNode.setId(item.getId());
            easyUiTreeNode.setText(item.getName());
            easyUiTreeNodeList.add(easyUiTreeNode);
        }
        return easyUiTreeNodeList;
    }

    public CommonResult updateNode(Long id, String name) {
        TbContentCategory contentCategory = contentCategoryMapper.selectByPrimaryKey(id);
        if(contentCategory!=null){
            contentCategory.setName(name);
        }
        if(contentCategoryMapper.updateByPrimaryKeySelective(contentCategory)>0){
            return CommonResult.ok(contentCategory);
        }
        return CommonResult.ok();
    }

    public CommonResult createNode(Long parentId, String name) {
        TbContentCategory tbContentCategory = new TbContentCategory();
        tbContentCategory.setName(name);
        tbContentCategory.setParentId(parentId);
        tbContentCategory.setIsParent(false);
        tbContentCategory.setSortOrder(1);
        tbContentCategory.setStatus(1);
        contentCategoryMapper.insert(tbContentCategory);
        Long id = tbContentCategory.getId();

        return CommonResult.ok(id);
    }

    public void deleteNode(Long id, Long parentId) {
        contentCategoryMapper.deleteByPrimaryKey(id);
    }
}
